package com.atguigu.jxc.controller;

import com.atguigu.jxc.domain.R;
import com.atguigu.jxc.entity.Customer;
import com.atguigu.jxc.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;


    //客户分页列表
    @PostMapping("list")
    public Map<String,Object> getCustomerList(Customer customer){
        //分页
        int page = customer.getPage();
        int rows = customer.getRows();
        String customerName = customer.getCustomerName();

        //获取分页数据
        List<Customer> customerList = customerService.getCustomerList(page, rows, customerName);


        //获取总条数
        Integer customerTotal = customerService.getCustomerTotal();

        Map<String,Object> map = new HashMap<>();
        map.put("rows",customerList);
        map.put("total",customerTotal);

        return map;
    }

    @PostMapping("save")
    public R save(Customer customer){
        String customerId = customer.getCustomerId();

        if(!StringUtils.isEmpty(customerId))
            customerService.updateById(customer);
        else
            customerService.save(customer);

        return R.ok(100,"请求成功",null);
    }

    @PostMapping("delete")
    public R delete(String[] ids){
        List<String> collect = Arrays.stream(ids).collect(Collectors.toList());
        for(String customerId : collect){
            customerService.deleteById(customerId);
        }

        return R.ok(100,"删除成功",null);
    }

}
